//code from qscite-4.0
#include <QtGui>
#include <QtDebug>
#include <QString>
#include <Qsci/qsciscintilla.h>

#include "FindText.h"
//#include "mainwindow.h"

dlgFindText::dlgFindText(QWidget* parent):QDialog(parent) {
  setupUi(this);
  connect(btnFind, SIGNAL(clicked()), this, SLOT(doSearch()));
  connect(comboBox, SIGNAL(editTextChanged(QString)), this, SLOT(onTextChange(QString)));
  //this->setAttribute(Qt::WA_DeleteOnClose);
  TextEdit = NULL;	
}

void dlgFindText::SetTextEdit(QsciScintilla* TextEdit)
{
	this->TextEdit=TextEdit;
  	Up = Down = 0;
	OnChangeTextEdit = true;	
}

void dlgFindText::doSearch() {
  if (btnFind->text() == "&Find") {
    expr = comboBox->currentText();
    regex = chkRegEx->isChecked();
    caseSens = chkCase->isChecked();
    wholeWord = chkWhole->isChecked();
    forward = !chkBackwards->isChecked();
    //bool result = parent->getCurDoc()->findFirst(expr, regex, caseSens, wholeWord, false, forward);
    bool result = TextEdit->findFirst(expr, regex, caseSens, wholeWord, false, forward);
    close();
    Down =0x01;	
    if( !result )
    {
	int ret = QMessageBox::warning(this, SoftwareName,
                     tr("no find text"),
                     QMessageBox::Ok);
     }	
  } 
  OnChangeTextEdit = false;
}

void dlgFindText::onTextChange(QString text) {
  text = ""; //don't care about the string, but making compiler happy
  btnFind->setText("&Find");
}

void dlgFindText::FindNext(void)
{
    //0 == false;
    //1 == true;
    if( TextEdit == NULL)
    	return ;
    if ( OnChangeTextEdit)
	return ;	
    bool result;
    Down = (Down & 0x01); 
    if(!Down)
    {	
    	result = TextEdit->findFirst(expr, regex, caseSens, wholeWord, false, forward);
    	Down = Down | 0x01;
    }
    else 
    {
	Down = Down | 0x02;	
	result = TextEdit->findNext();
    	if(!result)
    	{
	 	int ret = QMessageBox::warning(this, SoftwareName,
                     tr("find next finished"),
                     QMessageBox::Ok);
     	}
    }	
    Up = 0;		
}

void dlgFindText::FindPrevious(void)
{
    	if( TextEdit == NULL)
    		return ;	
    	if ( OnChangeTextEdit)
		return ;	
    	bool result = TextEdit->findFirst(expr, regex, caseSens, wholeWord, false, !forward);
	result = TextEdit->findNext();
	if(!result)
	{
		int ret = QMessageBox::warning(this, SoftwareName,
                     tr("find previous finished"),
                     QMessageBox::Ok );
	}
	Down = 0;	
}
